import React, {useEffect, useState} from 'react'
import {Button, Upload, Row, Col, Steps, message, Modal, Space} from 'antd'
import styles from './index.less'
import {downloadFileUrl, getTemplateUrl} from '@/service/common/download'
import CustomTable from '@/components/Table'
// 图标
import {IconFont} from '@/utils/common/tool'

const {Step} = Steps
type PropsType = {
	title?: string // 弹框标题
	isModalOpen: boolean // 弹框是否可见
	setIsModalOpen: React.Dispatch<React.SetStateAction<boolean>>
	importData: any // 导入保存方法
	onTableList: any // 获取导入失败表格数据
	getListData: any // 导入成功刷新列表数据
	downloadUrl?: string // 下载模板url
	uploadFileUrl?: string // 上传模板url
	fileNmae?: string
	columns: any
	id?: string
	dataId?: string
	type?: number | string
	saveType?: number | string
	goodsType?: string
	modular?: string
	sourceId?: number
	templateType?: string
	parkId?: string | number // 停车场id
	childCange?: any // 弹框关闭回调
	width?: any // 弹框大小
	getRetrunValue?: any // 获取列表返回值
	childState?: number // 用来判断table是否是表头分组
	typeUp?: boolean
	planId?: string // 盘点计划ID
	takeId?: any
	clue?: any // 渠道和线索返回值有特殊处理
	temporaryData?: any // 库位导入临时数据
}

const batchUpload = (props: PropsType) => {
	const {
		title = '批量导入',
		isModalOpen,
		setIsModalOpen,
		onTableList,
		getListData,
		importData,
		downloadUrl,
		uploadFileUrl,
		fileNmae = 'file',
		columns,
		id,
		dataId,
		type,
		saveType,
		goodsType,
		modular,
		sourceId,
		templateType,
		parkId,
		childCange,
		width,
		getRetrunValue,
		childState,
		typeUp = true,
		planId,
		takeId,
		clue,
		temporaryData = false,
	} = props
	const [current, setCurrent] = useState(0)
	const [show, setShow] = useState(true)
	const [errorList, setErrorList] = useState<any>([])
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [successCount, setSuccessCount] = useState(0)
	const [loading, setLoading] = useState(false)
	const [uploadId, setUploadId] = useState('')
	const [fileObj, setFileObj] = useState<any>()

	// 页码变化更新导入失败表格数据
	const getData = () => {
		setLoading(true)
		onTableList({...params, batch: uploadId})
			.then((res: any) => {
				if (!res?.success) {
					setLoading(false)
				}
				if (res?.success) {
					setTotal(res?.data?.total)
					// 如果表头分列，就需要对返回值做处理
					if (childState === 2) {
						const list = res?.data?.records
						// 循环遍历给合计赋值
						// eslint-disable-next-line no-shadow
						list?.forEach((res: any) => {
							res.collectAll = 0 // 补缴合计
							res.dedluctALL = 0 // 扣款合计
							res.retrunCount = 0 // 退还
							res.paymentCount = 0 // 补缴
							res?.collectList?.forEach((item: any) => {
								res[item.feeItemName] = item?.feeItemAmount
								// eslint-disable-next-line operator-assignment, no-unsafe-optional-chaining
								res.collectAll =
									// eslint-disable-next-line no-unsafe-optional-chaining
									Number(
										(
											Number(res?.collectAll) +
											Number(item?.feeItemAmount)
										).toFixed(2),
									)
							})
							res?.deductionList?.forEach((info: any) => {
								res[info.feeItemName] = info?.feeItemAmount
								// eslint-disable-next-line operator-assignment, no-unsafe-optional-chaining
								res.dedluctALL =
									// eslint-disable-next-line no-unsafe-optional-chaining
									Number(
										(
											Number(res?.dedluctALL) +
											Number(info?.feeItemAmount)
										).toFixed(2),
									)
							})
							// 计算给补缴/退还赋值
							// eslint-disable-next-line no-unsafe-optional-chaining
							if (res?.collectAll - res?.dedluctALL > 0) {
								// eslint-disable-next-line no-unsafe-optional-chaining
								res.retrunCount =
									// eslint-disable-next-line no-unsafe-optional-chaining
									Number(
										(
											Number(res?.collectAll) -
											Number(res?.dedluctALL)
										).toFixed(2),
									)
							} else if (res.collectAll - res.dedluctALL < 0) {
								// eslint-disable-next-line no-unsafe-optional-chaining
								res.paymentCount =
									// eslint-disable-next-line no-unsafe-optional-chaining
									Number(
										(
											Number(res?.dedluctALL) -
											Number(res?.collectAll)
										).toFixed(2),
									)
							} else {
								res.retrunCount = 0
								res.paymentCount = 0
							}
						})
						setErrorList(list)
					} else if (clue === '1') {
						const arr: any = []
						res?.data?.records?.forEach((arrItem: any) => {
							arr.push(arrItem?.clueImportVo)
						})
						setErrorList(arr)
					} else if (clue === '2') {
						const arr: any = []
						res?.data?.records?.forEach((arrItem: any) => {
							arr.push(arrItem?.ditchImportVo)
						})
						setErrorList(arr)
					} else if (temporaryData) {
						const newData = res?.data?.records?.map(
							(item: {temporaryData: string}) =>
								JSON.parse(item?.temporaryData),
						)
						setErrorList(newData)
					} else {
						setErrorList(res?.data?.records)
					}
					getRetrunValue?.(res?.data?.records)
					setLoading(false)
				}
			})
			.catch((error: any) => {
				message.error(error)
				setLoading(false)
			})
	}
	useEffect(() => {
		if (current === 1 || current === 2) {
			getData()
		}
	}, [params, current])

	const onCancel = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
		setShow(true)
		setCurrent(0)
		setIsModalOpen(false)
	}
	const onBack = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
		setShow(true)
		setCurrent(0)
		if (current === 0 || current === 2) {
			setIsModalOpen(false)
		} else {
			setCurrent(current - 1)
		}
	}

	// 批量处理提交
	const onBatchSubmit = async () => {
		if (current < 2) {
			setCurrent(current + 1)
		} else if (current === 2) {
			const query: any = {
				batch: uploadId,
			}
			if (dataId) {
				query.id = dataId
			}
			if (type && modular !== 'material') {
				query.type = type
			}
			if (saveType) {
				query.type = saveType
			}
			if (goodsType) {
				query.goodsType = goodsType
			}
			if (parkId) {
				query.parkId = parkId
			}
			const formdata = new FormData()
			const newFileNmae = fileNmae || 'excel'
			formdata.append(newFileNmae, fileObj)
			formdata.append('type', '2')
			formdata.append('takeId', takeId)
			if (planId) {
				formdata.append('file', fileObj)
				formdata.append('planId', planId)
			}
			importData(
				modular === 'material' || planId || takeId ? formdata : query,
			)
				.then((res: any) => {
					if (res.success) {
						onCancel()
						message.success('导入成功')
						getListData()
					}
				})
				.catch((error: any) => {
					message.error(error)
				})
		}
	}
	const uploadProps = {
		action: uploadFileUrl,
		name: fileNmae,
		data: {fleetId: id, type, goodsType, parkId, planId, takeId},
		beforeUpload: (file: any) => {
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.error('文件必须小于200MB')
			}
			return isLt200M
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				message.success('上传成功')
				setShow(false)
				setUploadId(info?.file?.response?.data?.batch)
				setSuccessCount(info?.file?.response?.data?.successCount)
				setFileObj(info?.file?.originFileObj)
			}
			if (info.file.status === 'error') {
				setShow(false)
				message.error(info?.file?.response.msg)
			}
		},
		onDrop() {},
		onRemove(info: any) {
			setShow(true)
			message.success(`${info?.name}移除成功`)
		},
	}
	// 关闭弹框回调
	const afterCloseFn = () => {
		if (childCange) {
			childCange(1)
		}
	}
	return (
		<Modal
			afterClose={afterCloseFn}
			title={title}
			open={isModalOpen}
			onCancel={onCancel}
			width={width || 720}
			destroyOnClose
			footer={
				<>
					<Button size="small" onClick={onBack}>
						{current === 0 ? '取消' : '上一步'}
					</Button>
					<Button
						type="primary"
						size="small"
						onClick={onBatchSubmit}
						disabled={current === 0 && show === true}>
						{current === 2 ? '保存' : '下一步'}
					</Button>
				</>
			}>
			<div className={styles.batchUpload}>
				<Row gutter={12}>
					<Col sm={{span: 22, offset: 1}}>
						<Steps current={current} labelPlacement="vertical">
							{typeUp ? (
								<Step title="下载模板，上传文件" />
							) : (
								<Step title="上传文件" />
							)}
							{/* <Step title="下载模板，上传文件" /> */}
							<Step title="文件导入，数据检测" />
							<Step title="确认结果，完成导入" />
						</Steps>
					</Col>
				</Row>
				{current >= 1 ? (
					<Row gutter={12}>
						<Col sm={{span: 24}}>
							<div className={styles.info}>
								<Space>
									<span style={{color: '@primary-color'}}>
										已成功{successCount}条
									</span>
									<span style={{color: '#FF2E30'}}>
										失败{total}条
									</span>
								</Space>
							</div>
						</Col>
						<Col sm={{span: 24}}>
							<div className="customTable">
								<CustomTable
									params={params}
									columns={columns}
									pagination
									total={total}
									callback={(pagination: any) => {
										setParams(pagination)
									}}
									loading={loading}
									dataSource={errorList}
								/>
							</div>
						</Col>
					</Row>
				) : (
					<Row gutter={12}>
						{typeUp ? (
							<Col sm={{span: 24}}>
								<div className="stepBox">
									<div className="inlineImg">
										<IconFont type="icon-xiazai" />
									</div>
									<div className="inlineText">
										<div className="inlineContent">
											<div className="text title">
												下载文件模板、填写导入信息
											</div>
											{sourceId ? (
												<Button
													type="primary"
													shape="round"
													size="small"
													className="downOrupload"
													onClick={() =>
														getTemplateUrl(
															sourceId,
															templateType,
														)
													}>
													下载模板
												</Button>
											) : (
												<a
													href={`${downloadFileUrl}/${downloadUrl}`}>
													<Button
														type="primary"
														shape="round"
														size="small"
														className="downOrupload">
														下载模板
													</Button>
												</a>
											)}
										</div>
									</div>
								</div>
							</Col>
						) : null}

						<Col sm={{span: 24}}>
							<div className="stepBox">
								<div className="inlineImg">
									<IconFont type="icon-a-shangchuan1" />
								</div>
								<div className="inlineText">
									<div className="inlineContent">
										<div className="text title">
											上传导入模板
										</div>
										<div className="text">
											支持文件xls、xlsx（即Excel表格），文件大小不得超过200M，最大支持导入50万条数据
										</div>
									</div>

									<>
										<Upload {...uploadProps}>
											{!show ? (
												''
											) : (
												<Button
													type="primary"
													shape="round"
													size="small"
													className="downOrupload">
													上传文件
												</Button>
											)}
										</Upload>
									</>
								</div>
							</div>
						</Col>
					</Row>
				)}
			</div>
		</Modal>
	)
}
export default batchUpload
